package com.influency.itlab.multi_thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

public class InfluencyLock implements Lock {
    private LinkedBlockingQueue<Thread> mQueue = new LinkedBlockingQueue<>();

    private AtomicReference<Thread> mKey = new AtomicReference<>(new Thread());
    @Override
    public void lock() {
        while(!mKey.compareAndSet(null,Thread.currentThread())){//0。偏向锁，先来先得，后来阻塞
            mQueue.add(Thread.currentThread());
            LockSupport.park();//1。当前线程阻塞，全部阻塞在此
            mQueue.remove(Thread.currentThread());//3。出队列-》0。抢锁
        }

    }

    @Override
    public void unlock() {
        if(mKey.compareAndSet(Thread.currentThread(),null)){
            for (Object object:mQueue.toArray()){
                Thread thread = (Thread) object;
                LockSupport.unpark(thread);//2。唤醒其他线程，全部解除阻塞
            }
        }

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long l, TimeUnit timeUnit) throws InterruptedException {
        return false;
    }



    @Override
    public Condition newCondition() {
        return null;
    }
}
